import React, { createElement } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { ConfigProvider } from "antd";
import zhCN from "antd/locale/zh_CN";
import { dark } from "@/theme";
import { persistor, store } from "@/redux/index";
import { PersistGate } from "redux-persist/integration/react";

export default function createModel(ReactComponent) {
  let container;
  let root;

  function ModelComponent(props) {
    return (
      <React.StrictMode>
        <ConfigProvider locale={zhCN} theme={dark}>
          <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
              <ReactComponent {...props} />
            </PersistGate>
          </Provider>
        </ConfigProvider>
      </React.StrictMode>
    );
  }

  const close = (callback) => {
    if (!container || !root) return;
    root.unmount();
    document.body.removeChild(container);
    container = undefined;
    root = undefined;
    callback && callback();
  };

  const open = (customProps) => {
    if (!container) {
      container = document.createElement("div");
      document.body.appendChild(container);
      root = createRoot(container);
    }

    const props = {
      ...customProps,
      close,
    };

    const component = createElement(ModelComponent, props);
    root.render(component);
    return component;
  };

  const openOnce = (customProps) => {
    if (container) return;
    container = document.createElement("div");
    document.body.appendChild(container);
    root = createRoot(container);
    const props = {
      ...customProps,
      close,
    };
    const component = createElement(ModelComponent, props);
    root.render(component);
    return component;
  };

  return {
    open,
    openOnce,
    close,
  };
}
